/*
 * @Author: sonss
 * @Date: 2024-03-03 21:36:46
 * @LastEditTime: 2024-03-08 16:45:25
 * @FilePath: /tencent-meeting-sdk-golang/qqmeeting/utils.go
 * @Description: 工具
 */
package qqmeeting

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"math/rand"
	"net/url"
	"strconv"
	"time"
)

// 默认URL Parameter处理方式
func defaultPlaceholderFiller(req MeetingRequest, args ...interface{}) string {
	return fmt.Sprintf(req.getDescriptor().Url, args...)
}

func PrintResponseJsonString(response MeetingResponse) string {
	result, _ := json.Marshal(response)
	log.Println(string(result))
	return string(result)
}

type KeyValuePair struct {
	Key   string
	Value string
}
type QueryValues []*KeyValuePair

func NewQueryValues() QueryValues {
	return make(QueryValues, 0, 2)
}

func (v *QueryValues) Add(key, value string) {
	*v = append(*v, &KeyValuePair{
		key, value,
	})
}

func (v *QueryValues) Encode() string {

	if len(*v) == 0 {
		return ""
	}
	var buf bytes.Buffer
	flag := false
	for _, v := range *v {
		if flag {
			buf.WriteString("&")
		} else {
			flag = true
		}
		buf.WriteString(fmt.Sprintf("%s=%s", url.QueryEscape(v.Key), url.QueryEscape(v.Value)))
	}
	return buf.String()
}

/**
 * @description: 随机数
 * @param {*} min
 * @param {int} max
 * @return {*}
 */
func Rand(min, max int) int {
	if min > max {
		panic("min: min cannot be greater than max")
	}
	// PHP: getrandmax()
	if int31 := 1<<31 - 1; max > int31 {
		panic("max: max can not be greater than " + strconv.Itoa(int31))
	}
	if min == max {
		return min
	}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	return r.Intn(max+1-min) + min
}
